package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var ticket = 10

var mutex sync.Mutex //创建锁头

var wg sync.WaitGroup // 同步等待组
func main() {
	/*
		模拟四个售票窗口
	*/

	wg.Add(4)

	go saleTickets("售票口1")
	go saleTickets("售票口2")
	go saleTickets("售票口3")
	go saleTickets("售票口4")

	wg.Wait()
	time.Sleep(5 * time.Second)
}

func saleTickets(name string) {
	rand.Seed(time.Now().UnixNano())
	defer wg.Done()
	for {
		// 上锁
		mutex.Lock()
		if ticket > 0 {
			time.Sleep(time.Duration(rand.Intn(1000)) * time.Microsecond)
			fmt.Println(name, "售出：", ticket)
			ticket--
		} else {
			// 解锁
			mutex.Unlock()
			fmt.Println(name, "售罄，没有票了。。。")
			break
		}
		// 解锁
		mutex.Unlock()
	}
}
